package com.example.musicaiap.ui.player

import androidx.lifecycle.viewModelScope
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.mvi.base.MviViewModel
import com.example.musicaiap.ui.player.PlayerContract.PlayerEffect
import com.example.musicaiap.ui.player.PlayerContract.PlayerIntent
import com.example.musicaiap.ui.player.PlayerContract.PlayerState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import com.example.musicaiap.data.repository.FavoriteStateRepository
import javax.inject.Inject

/**
 * 注意：我们移除了EventBus，改为直接使用FavoriteStateRepository作为单一数据源
 * 所有组件都应该从FavoriteStateRepository获取收藏状态
 */

/**
 * 播放器ViewModel，管理播放器状态和处理用户意图
 */
@HiltViewModel
class PlayerViewModel @Inject constructor(
    private val _playerController: PlayerController,
    private val favoriteStateRepository: FavoriteStateRepository
) : MviViewModel<PlayerState, PlayerIntent, PlayerEffect>() {

    val playerController: PlayerController
        get() = _playerController

    init {
        // 监听播放器状态
        observePlayerState()

        // 监听播放器副作用
        observePlayerEffects()
    }

    override fun createInitialState(): PlayerState = PlayerState()

    override fun handleIntent(intent: PlayerIntent) {
        when (intent) {
            is PlayerIntent.PlaySong -> {
                _playerController.play(intent.song)
            }
            is PlayerIntent.PlaySongs -> {
                _playerController.play(intent.songs, intent.startIndex)
            }
            is PlayerIntent.PlayPause -> {
                if (uiState.value.isPlaying) {
                    _playerController.pause()
                } else {
                    _playerController.resume()
                }
            }
            is PlayerIntent.SkipNext -> {
                _playerController.skipToNext()
            }
            is PlayerIntent.SkipPrevious -> {
                _playerController.skipToPrevious()
            }
            is PlayerIntent.SeekTo -> {
                _playerController.seekTo(intent.positionMs)
            }
            is PlayerIntent.SetPlaybackSpeed -> {
                _playerController.setPlaybackSpeed(intent.speed)
            }
            is PlayerIntent.SetRepeatMode -> {
                _playerController.setRepeatMode(intent.repeatMode)
            }
            is PlayerIntent.SetShuffleMode -> {
                _playerController.setShuffleMode(intent.enabled)
            }
            is PlayerIntent.ToggleFavorite -> {
                _playerController.toggleFavorite(intent.songId)
                // 不再需要通过EventBus通知，FavoriteStateRepository会自动通知所有观察者
            }
            is PlayerIntent.TogglePlayMode -> {
                togglePlayMode()
            }
        }
    }

    /**
     * 监听播放器状态变化
     * 优化版本：使用combine操作符同时监听播放器状态和收藏状态
     */
    private fun observePlayerState() {
        // 同时监听PlayerController状态和FavoriteStateRepository状态
        combine(
            _playerController.playerState,
            favoriteStateRepository.currentFavoriteState
        ) { playerState, isFavorite ->
            // 合并状态
            setState {
                copy(
                    currentSong = playerState.currentSong,
                    currentMediaItem = playerState.currentMediaItem,
                    playbackState = playerState.playbackState,
                    isPlaying = playerState.isPlaying,
                    currentPosition = playerState.currentPosition,
                    duration = playerState.duration,
                    playbackSpeed = playerState.playbackSpeed,
                    repeatMode = playerState.repeatMode,
                    shuffleModeEnabled = playerState.shuffleModeEnabled,
                    isFavorite = isFavorite, // 直接使用FavoriteStateRepository的状态
                    error = playerState.error,
                    playMode = _playerController.getPlayMode(),
                    currentPlaylist = playerState.currentPlaylist ?: emptyList()
                )
            }
        }.launchIn(viewModelScope)
    }

    /**
     * 监听播放器副作用
     */
    private fun observePlayerEffects() {
        viewModelScope.launch {
            _playerController.playerEffect.collectLatest { effect ->
                effect?.let {
                    when (it) {
                        is com.example.musicaiap.ui.player.PlayerEffect.PlaybackError ->
                            sendEffect(PlayerEffect.PlaybackError(it.message))
                        is com.example.musicaiap.ui.player.PlayerEffect.MediaItemTransition ->
                            sendEffect(PlayerEffect.MediaItemTransition(it.song))
                        is com.example.musicaiap.ui.player.PlayerEffect.PlaybackCompleted ->
                            sendEffect(PlayerEffect.PlaybackCompleted)
                        is com.example.musicaiap.ui.player.PlayerEffect.FavoriteChanged -> {
                            sendEffect(PlayerEffect.FavoriteChanged(it.isFavorite))
                            // 不再需要通过EventBus通知，FavoriteStateRepository会自动通知所有观察者
                        }
                        is com.example.musicaiap.ui.player.PlayerEffect.PlayModeChanged ->
                            sendEffect(PlayerEffect.PlayModeChanged(it.mode))
                    }
                }
            }
        }
    }

    /**
     * 处理用户意图的公共方法，供其他ViewModel调用
     */
    fun processIntent(intent: PlayerIntent) {
        handleIntent(intent)
    }

    /**
     * 释放资源
     */
    override fun onCleared() {
        super.onCleared()
        // 不需要在这里释放playerController资源，因为是单例
        // playerController会在应用结束时释放
    }

    private fun togglePlayMode() {
        val currentMode = uiState.value.playMode
        val nextMode = when (currentMode) {
            PlayerContract.PlayMode.SEQUENCE -> PlayerContract.PlayMode.SHUFFLE
            PlayerContract.PlayMode.SHUFFLE -> PlayerContract.PlayMode.REPEAT_ONE
            PlayerContract.PlayMode.REPEAT_ONE -> PlayerContract.PlayMode.REPEAT_ALL
            PlayerContract.PlayMode.REPEAT_ALL -> PlayerContract.PlayMode.SEQUENCE
        }

        _playerController.setPlayMode(nextMode)
        sendEffect(PlayerEffect.PlayModeChanged(nextMode))
    }
}